package com.tsyz.servlet.controller;

import com.alibaba.fastjson2.JSON;
import com.tsyz.servlet.context.UserContextHolder;
import com.tsyz.servlet.domain.dto.UserDTO;
import com.tsyz.servlet.domain.dto.req.UserDeleteUserReqDTO;
import com.tsyz.servlet.domain.dto.req.UserGetUserByIdReqDTO;
import com.tsyz.servlet.domain.dto.req.UserUpdateUserReqDTO;
import com.tsyz.servlet.domain.dto.resq.UserFindAllRespDTO;
import com.tsyz.servlet.domain.dto.resq.UserGetUserByIdRespDTO;
import com.tsyz.servlet.domain.mapstruct.*;
import com.tsyz.servlet.domain.po.UserPO;
import com.tsyz.servlet.domain.vo.Result;
import com.tsyz.servlet.domain.vo.req.UserCreateUserReqVO;
import com.tsyz.servlet.domain.vo.req.UserDeleteUserReqVO;
import com.tsyz.servlet.domain.vo.req.UserGetUserByIdReqVO;
import com.tsyz.servlet.domain.vo.req.UserUpdateReqVO;
import com.tsyz.servlet.domain.vo.resq.UserFindAllRespVO;
import com.tsyz.servlet.domain.vo.resq.UserGetUserByIdRespVO;
import com.tsyz.servlet.domain.vo.resq.UserInfoRespVO;
import com.tsyz.servlet.exception.ErrorEnumCode;
import com.tsyz.servlet.exception.ParamException;
import com.tsyz.servlet.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ext.zhaoke14
 */
@Slf4j
@RestController
@RequestMapping("/users")
public class UserApiController {

    @Autowired
    private UserService userService;

    /**
     * 获取所有用户列表
     *
     * @return Result对象，包含所有用户的列表
     */
    @GetMapping("findAll")
    public Result<List<UserFindAllRespVO>> findAll() {
        List<UserFindAllRespDTO> respDtoList = userService.findAll();
        List<UserFindAllRespVO> respVoList = UserFindAllRespVOMapper.INSTANCE.dtoToVo(respDtoList);
        return Result.success(respVoList);
    }

    /**
     * 根据用户ID获取用户信息
     *
     * @return 用户信息
     */
    @PostMapping("/getUserById")
    public Result<UserGetUserByIdRespVO> getUserById(@RequestBody @Valid UserGetUserByIdReqVO reqVo) {
        UserGetUserByIdReqDTO reqDTO = UserGetUserByIdReqDTOMapper.INSTANCE.voToDto(reqVo);
        UserGetUserByIdRespDTO respDTO = userService.getUserById(reqDTO);
        UserGetUserByIdRespVO respVO = UserGetUserByIdRespVOMapper.INSTANCE.dtoToVo(respDTO);
        return Result.success(respVO);
    }

    /**
     * 创建新用户
     *
     * @param userCreateUserReqVo 用户信息
     * @return 创建结果
     */
    @PostMapping("/addUser")
    public Result<UserPO> createUser(@RequestBody @Valid UserCreateUserReqVO userCreateUserReqVo) {

        UserDTO userDto = UserContextHolder.getCurrentUser();
        if (userDto == null) {
            return Result.error("未登录，无法创建用户");
        }

        // 转换DTO到实体
        UserPO userPO = UserPO.builder().name(userCreateUserReqVo.getName()).userName(userCreateUserReqVo.getUserName()).password(userCreateUserReqVo.getPassword()).email(userCreateUserReqVo.getEmail()).age(userCreateUserReqVo.getAge()).createTime(LocalDateTime.now()).updateTime(LocalDateTime.now()).createPin(userDto.getUserName()).updatePin(userDto.getUserName()).isDelete(0).build();


        UserPO resp = userService.createUser(userPO);
        return Result.success(resp);
    }

    /**
     * 更新用户信息
     *
     * @param userUpdateReqVo 更新的用户信息
     * @return 更新结果
     */
    @PostMapping("/updateUser")
    public Result<UserPO> updateUser(@RequestBody @Valid UserUpdateReqVO userUpdateReqVo) {
        UserDTO userDto = UserContextHolder.getCurrentUser();
        if (userDto == null) {
            throw new ParamException(ErrorEnumCode.PARAM_NULL);
        }
        if (userUpdateReqVo == null || userUpdateReqVo.getId() == null) {
            return Result.error("用户ID不能为空");

        }
        Long reqVoId = userUpdateReqVo.getId();
        UserGetUserByIdReqDTO reqDto = UserGetUserByIdReqDTOMapper.INSTANCE.voToDto(userUpdateReqVo);
        UserGetUserByIdRespDTO respDto = userService.getUserById(reqDto);
        if (respDto == null) {
            return Result.error("用户不存在");
        }

        // 更新用户信息
        respDto.setName(userUpdateReqVo.getName());
        respDto.setUserName(userUpdateReqVo.getUserName());
        respDto.setEmail(userUpdateReqVo.getEmail());
        respDto.setAge(userUpdateReqVo.getAge());
        respDto.setUpdateTime(LocalDateTime.now());
        respDto.setUpdatePin(userDto.getUserName());

        // 如果提供了密码，则更新密码
        if (StringUtils.isNotBlank(userUpdateReqVo.getPassword())) {
            respDto.setPassword(userUpdateReqVo.getPassword());
        }
        respDto.setIsDelete(userUpdateReqVo.getIsDelete());

        UserUpdateUserReqDTO updateUserReqDto = UserUpdateUserReqDTOMapper.INSTANCE.dtoToDto(respDto);
        UserPO resp = userService.updateUser(updateUserReqDto);
        return Result.success(resp);
    }

    /**
     * 删除用户
     *
     * @param reqVo 用户ID
     * @return 删除结果
     */
    @PostMapping("/deleteUserById")
    public Result<String> deleteUser(@RequestBody @Valid UserDeleteUserReqVO reqVo) {
        UserDTO userDto = UserContextHolder.getCurrentUser();
        if (userDto == null) {
            return Result.error("未登录，无法删除用户");
        }

        // 模拟查找用户
        UserGetUserByIdReqDTO reqDto = UserGetUserByIdReqDTOMapper.INSTANCE.voToDto(reqVo);
        UserGetUserByIdRespDTO respDto = userService.getUserById(reqDto);
        if (respDto == null) {
            return Result.error("用户不存在");
        }

        UserDeleteUserReqDTO deleteReqDto = UserDeleteUserReqDTOMapper.INSTANCE.voToDto(reqVo);
        boolean resp = userService.deleteUser(deleteReqDto);
        if (resp) {
            return Result.success("用户删除成功");
        } else {
            return Result.error("用户删除失败");
        }
    }

    @GetMapping("/info")
    public Result<UserInfoRespVO> getInfo() {
        UserDTO userDto = UserContextHolder.getCurrentUser();
        if (userDto != null) {
            UserInfoRespVO userInfoRespVO = UserInfoRespVO.builder()
                    .id(userDto.getId())
                    .userName(userDto.getUserName())
                    .email(userDto.getEmail())
                    .build();

            Result<UserInfoRespVO> success = Result.success(userInfoRespVO);

            // 分别测试各个部分的序列化
            log.debug("userInfoRespVO JSON: {}", JSON.toJSONString(userInfoRespVO));
            log.debug("Result.data JSON: {}", JSON.toJSONString(success.getData()));
            log.info("获取当前用户信息-出参:{}", JSON.toJSONString(success));

            return success;
        }

        return Result.success(null);
    }

}
